<template>
  <div>
    <HuilanBasicToolbar>
      <el-button
        v-if="permissionList.addBtn"
        type="primary"
        size="small"
        @click="handleAdd(true)"
        >{{ $t("aicosCommon.addBtn") }}</el-button
      >
    </HuilanBasicToolbar>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      ref="crud"
      v-model="form"
      :page.sync="page"
      :before-open="beforeOpen"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
      :upload-after="uploadAfter"
      :upload-before="uploadBefore"
      :upload-exceed="uploadExceed"
    >
      <template slot-scope="{ row }" slot="menu">
        <el-button
          v-if="permissionList.addBtn && row.type === 0"
          size="small"
          type="text"
          @click="handleAddSon(row)"
          >{{ $t("productList.addSonProduct") }}</el-button
        >
        <el-button
          v-if="permissionList.editBtn"
          size="small"
          type="text"
          @click="handleEdit(row)"
        >
          {{ $t("aicosCommon.editBtn") }}
        </el-button>
        <el-button
          v-if="permissionList.delBtn"
          size="small"
          type="text"
          @click="handleDel(row)"
          >{{ $t("aicosCommon.delBtn") }}</el-button
        >
      </template>
    </avue-crud>
  </div>
</template>
<script>
import {
  getList,
  addOrUpdate,
  remove,
} from "@/api/operatingCenter/productList";
import { baseURL } from "@/api/common";
import serviceList from "@/config/serviceList";
import { getTextWidth } from "@/util/util";
import { getRules } from "@/util/regx";
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      loading: false,
      data: [],
      form: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectRow: {},
      option: {
        header: false,
        editBtn: false,
        delBtn: false,
        dialogClickModal: false,
        viewBtn: false,
        labelWidth: 110,
        menuAlign: "center",
        rowParentKey: "parentSaasProductId",
        dialogWidth: "40%",
        dialogType: "drawer",
        dialogCustomClass: "huilan-drawer-form",
        emptyText: this.$t("aicosCommon.notData"),
        column: [
          {
            label: this.$t("productList.productName"),
            prop: "name",
            span: 24,
            overHidden: true,
            maxlength: 50,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message:
                  this.$t("aicosCommon.pleaseInput") +
                  this.$t("productList.productName"),
                trigger: "blur",
              },
              ...getRules(["charNumHan"]),
            ],
          },
          {
            label: this.$t("productList.productUrl"),
            prop: "linkUrl",
            span: 24,
            overHidden: true,
            maxlength: 100,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message:
                  this.$t("aicosCommon.pleaseInput") +
                  this.$t("productList.productUrl"),
                trigger: "blur",
              },
            ],
          },
          {
            label: this.$t("productList.systemCode"),
            prop: "systemCode",
            span: 24,
            maxlength: 50,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message:
                  this.$t("aicosCommon.pleaseInput") +
                  this.$t("productList.systemCode"),
                trigger: "blur",
              },
              ...getRules(["charNum"]),
            ],
          },
          {
            label: this.$t("productCenter.productType"),
            prop: "type",
            type: "select",
            span: 24,
            disabled: true,
            dicData: [
              {
                label: this.$t("productCenter.parentProduct"),
                value: 0,
              },
              {
                label: this.$t("productCenter.sonProduct"),
                value: 1,
              },
            ],
            value: 0,
          },
          {
            label: this.$t("productList.productCode"),
            prop: "value",
            span: 24,
            overHidden: true,
            maxlength: 50,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message:
                  this.$t("aicosCommon.pleaseInput") +
                  this.$t("productList.productCode"),
                trigger: "blur",
              },
              ...getRules(["charNum"]),
            ],
            formatter: (val, value, label) => {
              if (this.validatenull(value)) {
                return "--";
              }
              return label;
            },
          },
          {
            label: this.$t("productList.productLogo"),
            prop: "pic",
            hide: true,
            type: "upload",
            listType: "picture-img",
            limit: 1,
            accept: "image/*",
            // fileSize: 2048,
            autoUpload: false,
            uploadBefore: this.uploadBefore,
            span: 24,
            data: {
              fromSystemName: "base",
            },
            propsHttp: {
              res: "data",
              url: "newFileName",
              name: "oldFileName",
            },
            tip: this.$t("productList.productLogoTip"),
            action: `${baseURL}api/${serviceList.file}/miniofile/upload`,
            rules: [
              {
                required: true,
                message:
                  this.$t("appStore.manage.pleaseUpload") +
                  this.$t("productList.productLogo"),
                trigger: "blur",
              },
              //...getRules(['charNumHanUnderline'])
            ],
          },
          {
            label: this.$t("productList.specUrl"),
            prop: "specUrl",
            hide: true,
            span: 24,
          },
          {
            label: this.$t("productList.productDesc"),
            prop: "desc",
            type: "textarea",
            span: 24,
            maxlength: 300,
            showWordLimit: true,
            overHidden: true,
            formatter: (val, value, label) => {
              if (this.validatenull(value)) {
                return "--";
              }
              return label;
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["permission", "language"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permission["naoai-product-addOrEdit"],
          false
        ),
        delBtn: this.vaildData(this.permission["naoai-product-del"], false),
        editBtn: this.vaildData(
          this.permission["naoai-product-addOrEdit"],
          false
        ),
      };
    },
  },

  mounted() {},

  methods: {
    uploadBefore(file, done, loading) {
      const isSize = Number(file.size / 1024) < 2048;
      const isType =
        file.type == "image/png" ||
        file.type == "image/jpg" ||
        file.type == "image/jpeg" ||
        file.type == "image/webp";

      if (isSize && isType) {
        done();
      } else if (!isSize) {
        this.$message.error(this.$t("appStore.manage.fileSize"));
        loading();
      } else if (!isType) {
        this.$message.error(this.$t("appStore.manage.errorFileFormat"));
        loading();
      }
    },
    uploadAfter(res, done /*loading*/) {
      res.newFileName = `${baseURL}` + res.newFileName.substring(1);
      done(res);
    },
    uploadExceed() {
      this.$message.error("超出上传限制文件数量");
    },
    handleAddSon(row) {
      this.selectRow = row;
      this.form.type = 1;
      this.handleAdd();
    },
    handleAdd(flag = false) {
      if (flag) {
        this.form.type = 0;
        this.selectRow = {};
      }
      this.$refs.crud.rowAdd();
    },
    handleEdit(row) {
      this.$refs.crud.rowEdit(row);
    },
    handleDel(row) {
      this.$refs.crud.rowDel(row);
    },
    rowSave(row, done, loading) {
      let item = this.deepClone(row);
      if (!this.validatenull(this.selectRow)) {
        item.parentSaasProductId = this.selectRow.id;
      }
      const picArr = [];
      item.pic.map((item) => {
        picArr.push("/" + item.value.replace(`${baseURL}`, ""));
      });
      item.pic = picArr.join();
      addOrUpdate(item).then(
        (res) => {
          if (res.data.success) {
            this.$message.success(this.$t("aicosCommon.successOperate"));
            this.selectRow = {};
            this.onLoad(this.page);
            done();
          }
        },
        (error) => {
          console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      let picArr = [];
      const picArrTemp = [];
      if (Array.isArray(row.pic)) {
        picArr = row.pic;
        picArr.map((item) => {
          picArrTemp.push("/" + item.value.replace(`${baseURL}`, ""));
        });
      } else {
        picArr = row.pic.split(",");
        picArr.map((item) => {
          picArrTemp.push("/" + item.replace(`${baseURL}`, ""));
        });
      }

      row.pic = picArrTemp.join();
      addOrUpdate(row).then(
        (res) => {
          if (res.data.success) {
            this.$message.success(this.$t("aicosCommon.successOperate"));
            this.selectRow = {};
            this.onLoad(this.page);
            done();
          }
        },
        (error) => {
          console.log(error);
          loading();
        }
      );
    },
    rowDel(row, index, done) {
      this.$confirm(this.$t("aicosCommon.mutiDeleteConfirmTip"), {
        confirmButtonText: this.$t("aicosCommon.confirmBtn"),
        cancelButtonText: this.$t("aicosCommon.cancelBtn"),
        type: "warning",
      })
        .then(() => {
          return remove({ id: row.id });
        })
        .then(() => {
          this.$message({
            type: "success",
            message: this.$t("aicosCommon.successOperate"),
          });
          // 数据回调进行刷新
          done(row);
          this.onLoad(this.page);
        });
    },
    beforeOpen(done, type) {
      if (type == "view" || type == "edit") {
        if (this.form.pic) {
          const picArr = this.form.pic.split(",");
          const picArrTemp = [];

          picArr.map((item) => {
            picArrTemp.push(`${baseURL}` + item.substring(1));
          });
          this.form.pic = picArrTemp.join();
        }
      }
      const pic = this.findObject(this.option.column, "pic");
      if (this.form.type === 0) {
        pic.rules = [
          {
            required: true,
            message:
              this.$t("appStore.manage.pleaseUpload") +
              this.$t("productList.productLogo"),
            trigger: "blur",
          },
        ];
      } else {
        pic.rules = [];
      }
      this.option.labelPosition = this.language === "en" ? "top" : "right";
      done();
    },
    onLoad() {
      this.loading = true;
      const dataParam = {
        languageContentType: 2,
      };
      getList(dataParam).then((res) => {
        if (res.data.success) {
          this.data = res.data.data;
          this.data.map((item) => {
            item.children = [];
            if (!this.validatenull(item.subSaaSProduct)) {
              item.children = item.subSaaSProduct;
            }
          });
          if (this.language !== "zh") {
            this.option.column.forEach((item) => {
              let width = getTextWidth(item.label).nodeWidth + 100;
              this.$set(item, "width", width);
            });
          }
          this.loading = false;
        }
      });
    },
  },
};
</script>
